/**
 * input-tree v0.0.1
 */
(function($){
	$.fn.inputTree = function(){
		var _this = this;
		var _name=$(this).attr('name');	
		var _dataid = $(this).attr('data-id');
		var _chkStyle = $(this).attr('check-style');
		var _url = $(this).attr('url');
		var _title = $(this).attr('title');
		
		var _key = $(this).attr('key');
		var _keyValue = $(this).attr('key-value');
		var _pId = $(this).attr('p-id');
		
		//若input中不包含name，则初始化name值
		if(!_name){
			var randNum = function GetRandomNum(Min,Max){   
							var Range = Max - Min;   
							var Rand = Math.random();   
							return(Min + Math.round(Rand * Range));   
						}
			_name = new Date().getTime()+randNum(1,10000);
		}
		
		//修改当前input的type为hidden
		$(this).attr('type','hidden');		
		//当前元素前面追加show input
		var _showstr = "<input type='text' class='input-text' id='"+_name+"_show' name='"+_name+"_show' readOnly/>";
		$(this).before(_showstr);
		
		//绑定value事件
		var _buttnstr = "<div class=\"page-container\"><div align=\"center\">";
			_buttnstr +="<button id=\""+_name+"_ok\" class=\"btn btn-primary radius\"><i class=\"Hui-iconfont\">&#xe6a7;</i> 选择</button>&nbsp;&nbsp;";
			_buttnstr +="<button id=\""+_name+"_clear_close\" class=\"btn btn-danger radius\"><i class=\"Hui-iconfont\">&#xe609;</i> 清空</button>&nbsp;&nbsp;";
			_buttnstr +="<button id=\""+_name+"_close\" class=\"btn btn-default radius\"><i class=\"Hui-iconfont\">&#xe6a6;</i> 关闭</button>";
			_buttnstr +="</div></div>";
			_buttnstr +="<ul id=\""+_name+"_tree\" class=\"ztree\"></ul>";
		var _showtree = "<div style='display:none;'><ul id=\""+_name+"_show_tree\" class=\"ztree\"></ul></div>";
		$(this).after(_showtree);
		
		/**
		 * 默认radio
		 */
		var setting = {
            check: {
                enable: true,
                chkStyle: "radio",
                chkboxType: { "Y" : "ps", "N" : "ps" }
            },
            data: {
            	key:{
            		name:"name"
            	},
                simpleData: {
                        enable: true,
                        idKey: "id"
                }
            },
            async: { 
                type: "post",
                enable: true,
                url: _url
            }
	    };
		if(_key){
			setting.data.simpleData.idKey=_key;
		}
		if(_keyValue){
			setting.data.key.name=_keyValue;
		}
		if(_pId){
			setting.data.simpleData.pIdKey=_pId;
		}
		if(_chkStyle){
			setting.check.chkStyle=_chkStyle;
		}
		if(_dataid){
			setting.async.url = setting.async.url+'?cacheKey='+_dataid;
		}
		$.fn.zTree.init($("#"+_name+"_show_tree"), setting);//初始化树对象用于自动加载value值

		var initValueName = function(){
			var _value = $(_this).val();
			if(_value){
				var _initTree = $.fn.zTree.getZTreeObj(_name+"_show_tree");
				//初始化value对应name值
				var values  = _value.split(",");
				for(var i=0;i<values.length;i++){
					var checkValue = values[i];
					var nodes = _initTree.getNodes();
					var names = "";
					var _flag = 0;
					for(var j=0;j<nodes.length;j++){
						var node = nodes[j];
						if(checkValue==node[setting.data.simpleData.idKey]){
							if (names != '') names += ',';
							names +=node[setting.data.key.name];
							_flag = _flag+1;
						}
						//性能优化
						if(values.length==_flag){
							break;
						}
					}
					$("#"+_name+"_show").val(names);
				}
				var _initName = $("#"+_name+"_show").val();
				if(_initName){
					clearTimeout(_timer_id); //若触发了值的改变，则停止定时器
				}				
			}			
		}
		/**
		 * 定时器监听hidden值改变，并更新valueName
		 */
		var _timer_id = setTimeout(initValueName,500);
		
		//绑定点击事件
		$("#"+_name+"_show").click(function(){
			var w = 350;
			var h = 400;
			if(setting.check.chkStyle == "checkbox"){
				w = 450;
				h = 500;
			}
			//弹出layer
			var index = layer.open({
				type: 1,
				area: [w+'px',h+'px'],
				fix: false, //不固定
				title: _title,
				content: _buttnstr
			});
			
		    $.fn.zTree.init($("#"+_name+"_tree"), setting);//初始化树对象a
		    //绑定选择事件
		    $("#"+_name+"_ok").click(function(){
		    	//获取当前选中
		    	var treeObj = $.fn.zTree.getZTreeObj(""+_name+"_tree");
				var nodes = treeObj.getCheckedNodes(true);
				var ids = '';	
				var names = '';
				for(var i=0; i<nodes.length; i++){
					var node = nodes[i];
					if (ids != '') ids += ',';
					if (names != '') names += ',';
					ids += node[setting.data.simpleData.idKey];
					names += node[setting.data.key.name];
				}
		    	$("#"+_name+"_show").val(names);
		    	$(_this).val(ids);
		    	layer.close(index);
		    });
		    //清空
			$("#"+_name+"_clear_close").click(function(){
				var treeObj = $.fn.zTree.getZTreeObj(_name+"_tree");
				treeObj.checkAllNodes(false);
				$("#"+_name+"_show").val('');
		    	$(_this).val('');
				layer.close(index)
			});
			//关闭
			$("#"+_name+"_close").click(function(){				
				layer.close(index)
			});
		
		});
	}
}(jQuery))

$(function(){
	$(".input-tree").inputTree();
})